#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <termios.h>
#include <pthread.h>
#include "include/data_hand.h"
#include "include/sem.h"
#include <semaphore.h>
#include "include/data_global.h"
#include "include/mutex.h"

pthread_t save_thread;
pthread_t upload_thread;
pthread_t recv_thread;
pthread_t clientreq_thread;
pthread_t write_uart_pthread;
pthread_t infrared_pthread;
pthread_t sms_pthread;
pthread_t m0over_ctl_pthread;
pthread_t LED_thread;
pthread_t buz_thread;
pthread_t camera_thread;

void allpthread_create(void); //线程创建
void allpthread_join(void);//线程回收



int main(void)
{

    mutex_init();
   
    allpthread_create();//创建线程

    allpthread_join();//回收线程
    
    mutex_destory(); //将锁销毁

	return 0;
}


void allpthread_create(void) //线程创建
{

    if(pthread_create(&save_thread, NULL, DataSave_hand, NULL) < 0)
    {
        perror("fail to create save_thread");
        exit(-1);
    }
    //共享内存线程
    if(pthread_create(&upload_thread, NULL, DataUpload_hand, NULL) < 0)
    {
        perror("fail to create upload_thread");
        exit(-1);
    }
    //M0串口读线程
    if(pthread_create(&recv_thread, NULL, recv_hand, NULL) < 0) 
    { 
        perror("fail to create recv_thread");
        exit(-1);
    }
    //客户端请求下行主线程
    if(pthread_create(&clientreq_thread, NULL, pthread_client_request, NULL) < 0)
    {

        perror("fail to create clientreq_thread");
        exit(-1);
    }
    //M0串口写进程
    if(pthread_create(&write_uart_pthread, NULL, pthread_uart_cmd, NULL) < 0)
    {

        perror("fail to create pthread_uart_cmd");
        exit(-1);
    }
    //红外线程
    /*if(pthread_create(&infrared_pthread, NULL, pthread_infrared, NULL) < 0)
      {

      perror("fail to create infrared_pthread");
      exit(-1);
      }*/

    //环境信息超过上限报警线程
    if(pthread_create(&m0over_ctl_pthread, NULL, pthread_M0over_ctl, NULL) < 0)
    {

        perror("fail to create m0over_ctl_pthread");
        exit(-1);
    }
    if(pthread_create(&LED_thread, NULL, pthread_led, NULL) < 0)
    {

        perror("fail to create LED_thread");
        exit(-1);
    }
    if(pthread_create(&buz_thread, NULL, pthread_buzzer, NULL) < 0)
    {

        perror("fail to create buz_thread");
        exit(-1);
    }
    if(pthread_create(&camera_thread, NULL, pthread_camera, NULL) < 0)
    {

        perror("fail to create camera_thread");
        exit(-1);
    }

}
void allpthread_join(void)//线程回收
{
    pthread_join(write_uart_pthread, NULL);
    pthread_join(clientreq_thread, NULL);
    pthread_join(recv_thread, NULL);
    pthread_join(save_thread, NULL);
    pthread_join(upload_thread, NULL);
    pthread_join(infrared_pthread, NULL);
    pthread_join(m0over_ctl_pthread, NULL);
    pthread_join(LED_thread, NULL);
    pthread_join(buz_thread, NULL);
    pthread_join(camera_thread, NULL);


}
